package com.fb;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.StateListDrawable;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;
import com.dev.CheckableItem;
import com.dev.GUI;
import com.dev.HtmlBrowser;
import com.dev.HtmlIndentEditor;
import com.dev.IconView;
import com.dev.IconViewPlusChar;
import com.dev.IndentEditor;
import com.dev.JavaIndentEditor;
import com.dev.MainActivity;
import com.dev.QueryPaste;
import com.dev.R;
import com.dev.Search;
import com.dev.ShowFileClipBoard;
import com.dev.TabData;
import com.log;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import com.dev.FileBrowserPageHelper;
public class FileBrowserPage extends LinearLayout implements OnClickListener,OnLongClickListener{
	public final MainActivity ma;
	public final static String s1="indentItems";
    public String[] names;
	public TabData.FileBrowserInfo fbi;
    public Thread willshowIconLoaders[];
    public Thread iconLoaderNow;
    public CheckFilesAttr cfa;
    public Bitmap willshowIcons[];
    public Bitmap willshowIconsSub[][];//public TreeNode willshowTree[][];
	public int willshowSortedLen;
	public int willshowLen=0;//public int willshowCount;
	public int sort;
	public int dyn;
    public int der;
	public int pageIndex;
    public int willshowSizes[];
    public int willshowSorted[];
    public int willshowAttr[];
    public long willshowChildCount[];
    public byte willshowIndents[];
	public boolean selected[]=null;
	public boolean editorCanSave;
	public boolean folderOnBefore=true;
	public boolean fileOnBefore;
	public boolean indentItem;
	public boolean showHidden=true;
    public boolean willshowOpened[];
    public boolean willshowOpenedSub[][];
    public WrapData willshowWds[];
	public DirectoryListView dlv;
	public FileNavigator fn;
	public File home;
    public File willshow[];
    public File willshowSub[][];
    public File currentDirectory;
	public View view;
	public LayoutParams pageLayoutParams=new LayoutParams(-1,0,1f);
	public LinearLayout toolsbar;
	public IconView ivAdd,ivBack,ivForward,ivGoParent,ivRefresh,ivHome,ivSearch;
	public IconView ivPaste,ivSetting,ivMeans;
	public IconView box;
	public static int borderColor=0xff928337;
	public static int borderWidth=3;
    public LinkedList<Thread> tasks=new LinkedList<Thread>();
	public LinkedList<File> backable=new LinkedList<File>();
	public LinkedList<File> forwable=new LinkedList<File>();
	public IndentEditor ie;
	public HtmlIndentEditor hie;
	public JavaIndentEditor jie;
	public HtmlBrowser hb;
	public File file=null;
	public File[] files;
	public ViewGroup.LayoutParams itemlp;
	public static Bitmap typefile;
	public static Bitmap folder;
	public static Bitmap typec,typecpp;
	public static Bitmap typetxt;
	public static Bitmap typearchive;
	public static Bitmap typeApk;
	public static Bitmap typeImage;
	public static Bitmap typeImageBroken;
	public static Bitmap typePdf;
	public static Bitmap typeMusic;
	public static Bitmap typeJava;
	public static Bitmap typeSvg;
	public static Bitmap typeHtml;
	public static boolean inertia=false;
	public final static ColorMatrixColorFilter hidden=new ColorMatrixColorFilter(new float[]{
        1,0,0,0,0,
        0,1,0,0,0,
        0,0,1,0,0,
        0,0,0,1,-150,
    });
    static QueryForPick qfp;
	int[] willshow_ps;
	int[] willshowCounts;
	int[] willshowStarts;
	int[] willshowSorted_is;
	int[] willshowSortedStarts;
	PackageManager pm;
	public FileBrowserPage(MainActivity ma){
		super(ma);
		this.ma=ma;
		setOrientation(VERTICAL);
		pm=ma.getPackageManager();
		//indentItem=ma.shr.getBoolean(s1,true);
		fn=new FileNavigator(this);
		dlv=new DirectoryListView(this);
		ivAdd=new IconViewPlusChar(ma);
		box=new CheckableItem.Box(ma);
		box.setVisibility(View.GONE);
		box.setOnClickListener(this);
		box.setOnLongClickListener(this);
		ivAdd.setOnClickListener(this);
		ivAdd.setBackground(new Pressed());
		ivAdd.scaleWidth=3/2f;
		ivBack=new IconView(ma);
		ivBack.setImageResource(R.drawable.back);
		ivBack.setBackground(new Pressed());
		ivBack.setOnClickListener(this);
		ivForward=new IconView(ma);
		ivForward.setImageResource(R.drawable.forward);
		ivForward.setBackground(new Pressed());
		ivForward.setOnClickListener(this);
		ivGoParent=new IconView(ma);
		ivGoParent.setImageResource(R.drawable.ic_arrow_back);
		ivGoParent.setPadding(0,0,(int)(10*ma.dp),0);
		ivGoParent.setBackground(new Pressed());
		ivGoParent.setOnClickListener(this);
		ivRefresh=new IconView(ma);
		ivRefresh.setImageResource(R.drawable.ic_refresh);
		ivRefresh.setBackground(new Pressed());
		ivRefresh.setOnClickListener(this);
		ivHome=new IconView(ma);
		ivHome.setImageResource(R.drawable.ic_home);
		ivHome.setBackground(new Pressed());
		ivHome.setOnClickListener(this);
		ivSearch=new IconView(ma);
		ivSearch.setImageResource(R.drawable.ic_search);
		ivSearch.setBackground(new Pressed());
		ivSearch.setOnClickListener(this);
		ivPaste=new IconView(ma);
		ivPaste.setOnClickListener(this);
		ivPaste.setOnLongClickListener(this);
		ivPaste.setImageResource(R.drawable.ic_paste);
		ivPaste.setVisibility(View.GONE);
		ivSetting=new IconView(ma);
		ivSetting.setOnClickListener(this);
		ivSetting.setOnLongClickListener(this);
		ivSetting.setImageResource(R.drawable.ic_settings_black);
		ivMeans=new IconView(ma);
		ivMeans.setOnClickListener(this);
		ivMeans.setOnLongClickListener(this);
		if(indentItem){
			ivMeans.setImageResource(R.drawable.ic_arrow_compass);
		}else{
			ivMeans.setImageResource(R.drawable.finger_south);
		}
		LinearLayout.LayoutParams toolsbar_lp=new LinearLayout.LayoutParams(-2,-1);
		toolsbar=new LinearLayout(ma);
		toolsbar.setOrientation(HORIZONTAL);
		toolsbar.addView(ivAdd,toolsbar_lp);
		toolsbar.addView(ivGoParent,toolsbar_lp);
		toolsbar.addView(ivBack,toolsbar_lp);
		toolsbar.addView(ivForward,toolsbar_lp);
		toolsbar.addView(ivRefresh,toolsbar_lp);
		toolsbar.addView(ivHome,toolsbar_lp);
		toolsbar.addView(ivSearch,toolsbar_lp);
		toolsbar.addView(ivMeans,toolsbar_lp);
		toolsbar.addView(ivPaste,toolsbar_lp);
		toolsbar.addView(new Space(ma),new LayoutParams(0,-1,1));
		toolsbar.addView(box,toolsbar_lp);
		toolsbar.addView(ivSetting,toolsbar_lp);
		addView(fn,new LinearLayout.LayoutParams(-1,(int)(20*ma.dp)));
		addView(toolsbar,new LinearLayout.LayoutParams(-1,(int)(25*ma.dp)));
		addView(dlv,new LinearLayout.LayoutParams(-1,0,1));
        if(typefile==null){
            Resources res=getResources();
            typefile=BitmapFactory.decodeResource(res,R.drawable.file_type_unknown);
            folder=BitmapFactory.decodeResource(res,R.drawable.folder);
            typec=BitmapFactory.decodeResource(res,R.drawable.file_type_c);
            typecpp=BitmapFactory.decodeResource(res,R.drawable.file_type_cpp);
            typetxt=BitmapFactory.decodeResource(res,R.drawable.file_type_txt);
            typearchive=BitmapFactory.decodeResource(res,R.drawable.ic_zip_box);
            typeApk=BitmapFactory.decodeResource(res,R.drawable.format_apk);
            typeImage=BitmapFactory.decodeResource(res,R.drawable.format_picture);
            typeImageBroken=BitmapFactory.decodeResource(res,R.drawable.format_picture_broken);
            typePdf=BitmapFactory.decodeResource(res,R.drawable.ic_file_pdf);
            typeMusic=BitmapFactory.decodeResource(res,R.drawable.music);
            typeJava=BitmapFactory.decodeResource(res,R.drawable.file_type_java);
            typeSvg=BitmapFactory.decodeResource(res,R.drawable.file_type_svg);
            typeHtml=BitmapFactory.decodeResource(res,R.drawable.file_type_html);
        }
	}
    void atIconLoaderEnd(Thread loader,int index){
        if(loader==null)return;
        dlv.invalidate();
        iconLoaderNow=null;
        if(willshowSorted==null){
            int starty=dlv.startY;
            int vh=dlv.getHeight();
            for(;index<willshowLen&&starty<vh;index++){
                Thread th=willshowIconLoaders[index];
                if(th!=null){
                    if(th.getState()==Thread.State.NEW){
                        th.start();
                        iconLoaderNow=th;
                        break;
                    }
                }
                starty+=dlv.itemHeight;
            }
        }
        /*if(Looper.getMainLooper().isCurrentThread()){
            _ailf();
        }else{
            ma.runOnUiThread(new Runnable(){
                @Override 
                public void run(){
                    _ailf();
                }
            });
        }*/
    }
    void _ailf(){
        if(iconLoaderNow!=null){
            if(iconLoaderNow.getState()==Thread.State.TERMINATED){
                iconLoaderNow=null;
            }else return;
        }else return;
        invalidate();
    }
	
	public void letDir(File f){
		if(f.isDirectory()){
			if(f.canRead()){
                if(iconLoaderNow!=null)iconLoaderNow.interrupt();
				File[] list=f.listFiles();
				if(currentDirectory!=null)backable.push(currentDirectory);
                forwable.clear();
				currentDirectory=f;
				fn.setPath(f);
				setWillShow(list);
				ma.shr.edit().putString(GUI.browserNow,f.getAbsolutePath()).apply();
                
			}else{
				log.alert(getClass().getCanonicalName(),"setDir(File f):f.canRead()==false");
			}
		}
	}
	public void addWillShow(ArrayList<File> al){
		int size=al.size();
		int willshow_length_will=willshowLen+size;
		if(willshow_length_will<=willshow.length){
			for(int a=willshowLen,b=0;a<willshow_length_will;a++,b++){
				willshow[a]=al.get(b);
			}
		}else{
			File[] fs=new File[willshow_length_will+256];
			System.arraycopy(willshow,0,fs,0,willshowLen);
			for(int index=willshowLen,b=0;index<willshow_length_will;index++,b++){
				fs[index]=al.get(b);
			}
			willshow=fs;
		}
	}
	public void setWillShow(File[] willshow){
		willshowLen=willshow.length;
		this.willshow=willshow;
        willshowIndents=new byte[willshowLen];
		selected=null;
		box.setVisibility(GONE);
		box.setSelected(false);
        FileBrowserPageHelper.makeSort(this);
        if(willshowIcons==null||willshowIcons.length<willshowLen){
            willshowIcons=new Bitmap[willshowLen];
        }else{
            Arrays.fill(willshowIcons,0,willshowLen,null);
        }
        if(names==null||names.length<willshowLen){
            names=new String[willshowLen];
        }
        if(willshowAttr==null||willshowAttr.length<willshowLen){
            willshowAttr=new int[willshowLen];
        }
        if(willshowChildCount==null||willshowChildCount.length<willshowLen){
            willshowChildCount=new long[willshowLen];
        }
        for(int i=0;i<willshowLen;i++){
            names[i]=willshow[i].getName();
            willshowAttr[i]=0x10000000;
        }
        if(willshowIconLoaders==null||willshowIconLoaders.length<willshowLen){
            willshowIconLoaders=new Thread[willshowLen];
        }else{
            Arrays.fill(willshowIconLoaders,0,willshowLen,null);
        }
        dlv.invalidate();
	}
	@Override
	public boolean onLongClick(View v){
		if(v==ivPaste){
			if(ma.showFileClipBoard==null)ma.showFileClipBoard=new ShowFileClipBoard(ma);
			ma.showFileClipBoard.show(this);
		}else if(v==box){
			if(qfp==null)qfp=new QueryForPick(ma);
			qfp.show(this);
		}
		return true;
	}
	@Override
	public void onClick(View v){
		if(v==ivAdd){//onClick
			try{
			if(ma.whichTypeWillBeCreate==null)ma.whichTypeWillBeCreate=new WhichTypeWillBeCreate(ma);
			ma.whichTypeWillBeCreate.show(FileBrowserPage.this);
			}catch(Exception e){log.alert(e.toString());}
		}else if(v==ivGoParent){//onClick
            if(currentDirectory!=null){
                File parent=currentDirectory.getParentFile();
                if(parent==null)return;
                if(parent.canRead()){
                    backable.push(currentDirectory);
                    currentDirectory=parent;
                    fn.setPath(parent);
                    File[] list=parent.listFiles();
                    setWillShow(list);
                }else{
                    Toast.makeText(ma,"不可读",0).show();
                }
            }
			
		}else if(v==ivBack){//onClick
			if(backable.peek()!=null){
                ivBack.setColorFilter(null);
                ivBack.invalidate();
                File file=backable.pop();
                if(currentDirectory!=null){
                    ivForward.setColorFilter(null);
                    ivForward.invalidate();
                    forwable.push(currentDirectory);
                    currentDirectory=file;
                    fn.setPath(file);
                }else{
                    ivForward.setColorFilter(IconView.unable);
                    ivForward.invalidate();
                    currentDirectory=file;
                    fn.setPath(file);
                }
                File list[]=file.listFiles();
                setWillShow(list);
			}else{
				ivBack.setColorFilter(ivBack.unable);
			}
		}else if(v==ivForward){//onClick
			if(forwable.peek()!=null){
				File file=forwable.pop();
				backable.push(currentDirectory);
				currentDirectory=file;
				fn.setPath(file);
				File list[]=file.listFiles();
				setWillShow(list);
			}
		}else if(v==ivRefresh){//onClick
			if(currentDirectory!=null){
				File list[]=currentDirectory.listFiles();
				setWillShow(list);
				Toast.makeText(ma,"已刷新",0).show();
			}else if(der==10){
				ArrayList<File> fs=new ArrayList<File>();
				try{
					ContentResolver mContentResolver=ma.getContentResolver();
					Cursor c = mContentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
					int columnIndexOrThrow_DATA = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
					while(c.moveToNext()){
						String path = c.getString(columnIndexOrThrow_DATA);
						File f=new File(path);
						fs.add(f);
					}
				}catch(Exception e){
					log.alert(e.toString());
				}
				File[] files=new File[fs.size()];
				fs.toArray(files);
				this.files=files;
				setWillShow(files);
				Toast.makeText(ma,"已刷新",0).show();
			}
		}else if(v==ivHome){//onClick
			if(home==null)	{
				log.alert(getClass().getCanonicalName(),"home==null");
			}else if(currentDirectory==null){
				log.alert(getClass().getCanonicalName(),"currentDirectory==null");
			}else if(home.equals(currentDirectory)){
				Toast.makeText(ma,"无需此操作",0).show();
			}else{
				backable.push(currentDirectory);
				//log.alert("push",currentDirectory.getAbsolutePath());
				File list[]=home.listFiles();
				fn.setPath(home);
				setWillShow(list);

				forwable.clear();
				currentDirectory=home;
			}
		}else if(v==ivSearch){//onClick
			if(ma.search==null)ma.search=new Search(ma);
			ma.search.destination=currentDirectory;
			ma.search.show(this);
		}else if(v==ivPaste){//onClick
			if(ma.queryPaste==null)ma.queryPaste=new QueryPaste(ma);
			ma.queryPaste.startPaste(FileBrowserPage.this,currentDirectory);
		}else if(v==box){//onClick
			if(box.isSelected()){
				box.setSelected(false);
				if(willshowSorted==null){
					for(int index=0;index<selected.length;index++){
						//TreeNode tn=willshow[index];
						selected[index]=false;
						/*if(tn.opened){
							int count=tn.nodes.length;
							int end=index+count;
						}*/
					}
				}else{

				}
				dlv.invalidate();
			}else{
				box.setSelected(true);
				for(int i=0;i<selected.length;i++){
					selected[i]=true;
				}
				dlv.invalidate();
			}
		}else if(v==ivSetting){
			if(qs==null)qs=new QuerySettings(ma);
			qs.show(this);
		}else if(v==ivMeans){
			if(ivMeans.isSelected()){
				ivMeans.setSelected(false);
				ivMeans.setBackground(new Pressed());
			}else{
				ivMeans.setSelected(true);
				ivMeans.setBackground(new Selected());
			}
		}
	}
	static QuerySettings qs;
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		if(ma.fileClipBoard.size()>0){
			ivPaste.setVisibility(View.VISIBLE);
		}else{
			ivPaste.setVisibility(View.GONE);
		}
	}
	public static class Item extends TextView{
		public Item(MainActivity ma){
			super(ma);
			setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);
			setTextColor(0xff000000);
			setPadding(9,9,0,9);
			setTextSize(TypedValue.COMPLEX_UNIT_DIP,14);
			StateListDrawable sd=new StateListDrawable();
			sd.addState(new int[]{android.R.attr.state_pressed},new ColorDrawable(0x77888888));
			setBackground(sd);
		}

		@Override
		public void setEnabled(boolean enabled){
			if(enabled){
				setTextColor(0xff000000);
			}else{
				setTextColor(0xff999999);
			}
			super.setEnabled(enabled);
		}
	}
	public static class Pressed extends StateListDrawable{
		final int color=0x77999999;
		public Pressed(){
			addState(new int[]{android.R.attr.state_pressed},new ColorDrawable(color));
		}
	}
	public static class Selected extends StateListDrawable{
		public Selected(){
			addState(new int[]{android.R.attr.state_pressed},new ColorDrawable(0x00ffffff));
			addState(new int[]{0},new ColorDrawable(0x77999999));
		}
	}
}

